package safeCommitter.core.launcher.socket;

import java.util.LinkedList;
import java.util.List;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Path;
import org.eclipse.debug.core.ILaunchesListener2;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jface.preference.IPreferenceStore;

import safeCommitter.core.launcher.SCVMLauncher;
import safeCommitter.core.preferences.SCPreferenceConstants;
import safeCommitter.core.template.Activator;
import safeCommitter.utils.StringUtils;

/**
 * Executes a main class in a new JVM and starts a {@link SCSocketReader}.
 * 
 * 
 * @author Luiz Henrique
 * 
 */
public class SCVMSocketLauncher extends SCVMLauncher {

	private final SCSocketReader socket;

	public SCVMSocketLauncher(final IJavaProject project,
			final SCSocketReader socket) {
		super(project);
		this.socket = socket;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see safeCommitter.core.launcher.SCVMLauncher#runClazz(java.lang.Boolean,
	 * java.lang.Boolean, java.lang.String,
	 * org.eclipse.debug.core.ILaunchesListener2, java.lang.String[])
	 */
	@Override
	public void runClazz(Boolean debug, Boolean ignoreNGXmls,
			final String clazzName, final ILaunchesListener2 listener,
			final String... filePath) throws CoreException {
		IPreferenceStore preferenceStore = Activator.getDefault()
				.getPreferenceStore();
		Boolean searchTestNGFiles = preferenceStore
				.getBoolean(SCPreferenceConstants.P_ADD_TESTNG_XML)
				&& !ignoreNGXmls;
		String[] args = searchTestNGFiles ? new String[3] : new String[2];
		args[0] = filePath[0];
		int port = socket.getPort();
		args[1] = new String(String.valueOf(port));
		if (searchTestNGFiles) {
			args[2] = getCommaSeparatedTestNGFilesPath(preferenceStore
					.getString(SCPreferenceConstants.P_TESTNG_XML_PATH),
					project.getProject());
		}
		super.runClazz(debug, ignoreNGXmls, clazzName, listener, args);
		new Thread(socket).start();

	}

	public String getCommaSeparatedTestNGFilesPath(final String path,
			final IProject project) {
		String[] pathSplit = path.split(",");
		List<String> listToBeReturned = new LinkedList<String>();
		for (String s : pathSplit) {
			IResource member = project.findMember(new Path(s));
			if (member == null) {
				continue;
			}
			listToBeReturned.add(member.getLocation().toOSString());
		}
		return StringUtils.join(listToBeReturned.toArray(), ",", 0,
				listToBeReturned.size());
	}

}
